//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.ssy.lingxi.pay.utils.util;

import com.alibaba.fastjson.JSON;
import com.ssy.lingxi.pay.utils.AllInPayUtils;
import com.ssy.lingxi.pay.utils.Base64;
import com.ssy.lingxi.pay.utils.bean.PrivRequest;
import com.ssy.lingxi.pay.utils.bean.YunRequest;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.*;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
@Slf4j
public class YunClient {


        static {
            RSAUtil.publicKey = (RSAPublicKey)RSAUtil.loadPublicKey(null,null, null);
            RSAUtil.privateKey = (RSAPrivateKey)RSAUtil.loadPrivateKey(null,null, null);
            RSAUtil.tlPublicKey = (RSAPublicKey)RSAUtil.loadTLPublicKey(null);
        }

    // 当前类名
    private static String currentClassName = Thread.currentThread().getStackTrace()[1].getClassName();

    // 分配的系统编号
    public static String sysid = "1902271423530473681";

    // public static String publicKey ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEv2q2/xN5PF0dLn1vhIaVlyWsvJFVFxWgH7sQBObzYbZXOOVzoQpmXuSFOrF0/ol4Okd/2OGfdXUUFSUZfzAQOT1Wmjupec7z2V6l4/PT7aOg6t/MJwU9aW9Iw+AFzM1vnLOXdTlWVLZbtB7IiJ/HhfwBDkyvhp1zNYoAPrwC5QIDAQAB";
    // public static String privateKey = "MIID3jCCAsagAwIBAgILAZbujreifSA4bgAwDQYJKoZIhvcNAQEFB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KZvx4UDCNfxGnpWzQe99a8nqVl31FJ1V7tuiX5fYg8vJ/THkNrar28cEPJYeoC3nbFgS5UCsr1IO6F7UnU2wDjUsYvwXxlRIRDWUP5ulGfSnjQQfsYvcYkdLpsdEH6GvNaBGiEVpqDwV4bJzv9mhgAjEjBqUC8BtwIHoKeroApJHuUaqOQCnPfjO+GjVj2kv/ydgG57Gwc4c5sBbdzqOKQ==";
    private static Provider provider = new BouncyCastleProvider();

    // 测试环境接口地址：http://116.228.64.55:6900/service/soa
    public final static String testInterfaceURL = "http://116.228.64.55:6900/service/soa";
    // 测试环境网关地址：http://116.228.64.55:6900/yungateway/frontTrans.do
    public static String testGatewayURL = "http://116.228.64.55:6900/yungateway/frontTrans.do";
    // 测试环境门户地址：http://116.228.64.55:6901/portal
    public static String testPortalURL = "http://116.228.64.55:6901/portal";
    // 生产环境接口地址：https://fintech.allinpay.com/service/soa
    public static String procInterfaceURL = "https://fintech.allinpay.com/service/soa";
    // 生产环境网关地址：https://fintech.allinpay.com /yungateway/frontTrans.do
    public static String procGatewayURL = "http://fintech.allinpay.com/yungateway/frontTrans.do";
    // 生产环境门户地址：https://fintech.allinpay.com/portal
    public static String procPortalURL = "https://fintech.allinpay.com/portal";

    public static String request(YunRequest request) throws Exception {
        String resp = post(request);
            return verify(resp);
    }

    public static String encodeOnce(YunRequest request) throws Exception {
        Map<String, String> req = assembleReq(request);
        StringBuilder sb = new StringBuilder();

        String key;
        String value;
        for(Iterator var3 = req.entrySet().iterator(); var3.hasNext(); sb.append(key).append("=").append(URLEncoder.encode(value, "utf-8")).append("&")) {
            Entry<String, String> entry = (Entry)var3.next();
            key = (String)entry.getKey();
            value = (String)entry.getValue();
            if (value == null) {
                value = "";
            }
        }

        return sb.toString();
    }

    public static String encodeTwice(YunRequest request) throws Exception {
        Map<String, String> req = assembleReq(request);
        StringBuilder sb = new StringBuilder();
        Iterator var3 = req.entrySet().iterator();

        while(var3.hasNext()) {
            Entry<String, String> entry = (Entry)var3.next();
            sb.append((String)entry.getKey()).append("=").append(URLEncoder.encode(URLEncoder.encode((String)entry.getValue(), "utf-8"), "utf-8")).append("&");
        }

        return sb.toString();
    }

    private static String post(YunRequest request) throws Exception {
        String param = encodeOnce(request);
        StringBuilder result = new StringBuilder();
        BufferedWriter writer = null;
        BufferedReader reader = null;

        try {
            URL httpUrl = new URL(testInterfaceURL);
            HttpURLConnection connection = (HttpURLConnection)httpUrl.openConnection();
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8"));
            writer.write(param);
            writer.flush();
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));

            String line;
            while((line = reader.readLine()) != null) {
                result.append(line);
            }
        } catch (IOException var16) {
            var16.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }

                if (reader != null) {
                    reader.close();
                }
            } catch (IOException var15) {
                var15.printStackTrace();
            }

        }

        return result.toString();
    }

    private static Map<String, String> assembleReq(YunRequest request) throws Exception {
        String timeStr = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
        Map<String, String> req = new LinkedHashMap();
        if (request instanceof PrivRequest) {
            String privBizUserId = ((PrivRequest)request).getPrivBizUserId();
            req.put("privSysid", YunClient.sysid);
            req.put("privBizUserId", privBizUserId);
        } else {
            req.put("sysid", YunClient.sysid);
        }

        req.put("v", YunClient.sysid);
        req.put("timestamp", timeStr);
        req.put("sign", YunClient.sign(YunClient.sysid + request + timeStr));
        req.put("req", request.toString());
        return req;
    }

    private YunClient() {
    }

    public static String sign(String src) throws Exception {
        return AllInPayUtils.sign(src);
    }

    public static String verify(String resp) throws Exception {
        Map<String, String> respMap = (Map)JSON.parseObject(resp, Map.class);
        String value = (String)respMap.get("signedValue");
        String sign = (String)respMap.get("sign");
            if ("OK".equals(respMap.get("status"))) {
                Object obj = JSON.parse(value);
                if (obj instanceof Map) {
                    Map<String, Object> ret = (Map)obj;
                    if (ret.get("$PrimitiveReturn$") != null) {
                        respMap.put("returnValue", JSON.toJSONString(ret.get("$PrimitiveReturn$")));
                    }
                } else {
                    respMap.put("returnValue", value);
                }
            }

            return JSON.toJSONString(respMap);
        }


    public static String encrypt(String data) throws Exception {
        return RSAUtil.encrypt(data);
    }

    public static String decrypt(String data) throws Exception {
        return RSAUtil.decrypt(data);
    }

    public static RSAPublicKey generateRSAPublicKey(String modulus, String publicExponent) throws Exception {
        KeyFactory keyFac = null;

        try {
            keyFac = KeyFactory.getInstance("RSA", new BouncyCastleProvider());
        } catch (NoSuchAlgorithmException var6) {
            throw var6;
        }

        RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modulus, 16), new BigInteger(publicExponent, 16));

        try {
            return (RSAPublicKey)keyFac.generatePublic(pubKeySpec);
        } catch (InvalidKeySpecException var5) {
            throw var5;
        }
    }

    public static String md5(String src) {
        String result = "";

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            result = Base64.encode(md.digest(src.getBytes("utf-8")));
        } catch (Exception var3) {
            var3.printStackTrace();
        }

        return result;
    }

}
